//
//  MBChildRecordController.m
//  MiBaoTu
//
//  Created by 彭鹏 on 16/9/22.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBChildRecordController.h"
#import "MBPlayShowController.h"
#import "MBSendShowController.h"
#import <AVFoundation/AVFoundation.h>

typedef enum {
    IdentityType_record = 0,
    IdentityType_pauseRecord,
    IdentityType_continueRecord,
    
}IdentityType;

#define RECORD_MUSIC_PATH(fileName) ([MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.caf",fileName]])

@interface MBChildRecordController ()<AVAudioRecorderDelegate,AVAudioPlayerDelegate> {
    AVAudioSession              *_audioSession;
    AVAudioRecorder             *_audioRecorder;
    AVAudioPlayer               *_audioPlayer;
    NSTimer                     *_recordTimer;
    NSInteger                   secondIndex;   //时间
    UIButton                    *_contentBt;
    BOOL                        isBack;
}

@property (weak, nonatomic) IBOutlet UIButton *recordButton;

@property (weak, nonatomic) IBOutlet UISlider *sliderView;
@property (weak, nonatomic) IBOutlet UIButton *reRecord;
@property (weak, nonatomic) IBOutlet UIButton *promulgate;
@property (nonatomic,assign)IdentityType    identityType;
@property (weak, nonatomic) IBOutlet UILabel *recordShowTitleLb;

@property (weak, nonatomic) IBOutlet UIView *showContentLb;
@property (nonatomic,strong) NSString   *titleString;
@property (weak, nonatomic) IBOutlet UIImageView *bgImgView;

@end

@implementation MBChildRecordController

//判断麦克风权限
- (void)setRecordPermission
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        
        AVAudioSessionRecordPermission permissionStatus = [[AVAudioSession sharedInstance] recordPermission];
        
        switch (permissionStatus) {
            case AVAudioSessionRecordPermissionUndetermined:{
                NSLog(@"第一次调用，是否允许麦克风弹框");
                [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                    // CALL YOUR METHOD HERE - as this assumes being called only once from user interacting with permission alert!
                    if (granted) {
                        // Microphone enabled code
                    }
                    else {
                        // Microphone disabled code
                    }
                }];
                break;
            }
            case AVAudioSessionRecordPermissionDenied:
                // direct to settings...
                NSLog(@"已经拒绝麦克风弹框");
                [ErrorMessage showErrorMessage:@"请到设置中打开麦克风权限" inView:self.view];
                break;
            case AVAudioSessionRecordPermissionGranted:
                NSLog(@"已经允许麦克风弹框");
                // mic access ok...
                break;
            default:
                // this should not happen.. maybe throw an exception.
                break;
        }
        if(permissionStatus == AVAudioSessionRecordPermissionUndetermined) return;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    secondIndex = 0;
    isBack = NO;
    
    [self setBackItem];
    [self onCreateUI];
    [self.sliderView setThumbImage:[UIImage imageNamed:@"jiedian"] forState:UIControlStateNormal];
    
    if (_dataDic) {
        NSString *AudioName = [_dataDic objectForKey:@"AudioName"];
        AudioName = [AudioName componentsSeparatedByString:@"."][0];
        _titleString = AudioName;
        [self setTitleView:_titleString];
    } else {
        _titleString = @"";
    }
    
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    if ([fileManager fileExistsAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)]) {
        [fileManager removeItemAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME) error:nil];
    }
    [self setRecorderURL:[NSURL fileURLWithPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)] withSettings:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onGoToBack) name:@"MBSENDSHOW_NOTIFICATION" object:nil];
    [self setRecordPermission];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    if (_recordTimer) {
        [_recordTimer invalidate];
        _recordTimer = nil;
    }
}

- (void)setBackItem
{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 158*PERCEN)];
    
    [self.view addSubview:titleView];
    UIImage *img = [UIImage imageNamed:@"fanhui"];
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(10, 20+(44-img.size.height)/2., 80, img.size.height);
    [back setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 80-img.size.width)];
    [back setImage:img forState:UIControlStateNormal];
    [back setImage:img forState:UIControlStateHighlighted];
    [back addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:back];
    
    UILabel *titleLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 27, SCREEN_WIDTH, 30)];
    titleLb.text = [NSString stringWithFormat:@"%@",[_dataDic objectForKey:@"RecordName"]];
    titleLb.textAlignment = NSTextAlignmentCenter;
    titleLb.textColor = [UIColor whiteColor];
    [titleView addSubview:titleLb];
    
    UIButton *sendQZShowBt = [UIButton buttonWithType:UIButtonTypeCustom];
    sendQZShowBt.frame = CGRectMake(SCREEN_WIDTH-40, titleLb.top, 40, 30);
    
    [sendQZShowBt setImage:[UIImage imageNamed:@"wenhao"] forState:UIControlStateNormal];
    [sendQZShowBt setImage:[UIImage imageNamed:@"wenhao2"] forState:UIControlStateHighlighted];
    [sendQZShowBt addTarget:self action:@selector(onSendQZShowAction) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:sendQZShowBt];
}

- (void)onCreateUI
{
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, NAV_HEIGHT, SCREEN_WIDTH, _showContentLb.height-NAV_HEIGHT)];
    scrollView.backgroundColor = [UIColor clearColor];
    scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, 8);
    scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    [_showContentLb addSubview:scrollView];
    
    if (_lrcString.length > 0) {
//        NSString *text = _lrcString;
//        NSMutableString *mutString = [[NSMutableString alloc]init];
//        NSArray *array = [text componentsSeparatedByString:@"\n"];
//        for (int i = 0; i < [array count]; i++) {
//            NSString *linStr = [array objectAtIndex:i];
//            NSArray *lineArray = [linStr componentsSeparatedByString:@"]"];
//            if ([lineArray[0] length] > 8) {
//                NSString *str1 = [linStr substringWithRange:NSMakeRange(3, 1)];
//                NSString *str2 = [linStr substringWithRange:NSMakeRange(6, 1)];
//                if ([str1 isEqualToString:@":"] && [str2 isEqualToString:@"."]) {
//                    NSString *lrcStr = [lineArray objectAtIndex:1];
//                    [mutString appendString:lrcStr];
//                }
//            }
//        }
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
        style.lineSpacing = 10;
        style.alignment = NSTextAlignmentCenter;
//        style.firstLineHeadIndent = 20;
        
        NSMutableAttributedString *mutStr = [[NSMutableAttributedString alloc]initWithString:_lrcString];
        [mutStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12.f] range:NSMakeRange(0, _lrcString.length)];
        [mutStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, _lrcString.length)];
        
        UILabel *contentLb = [[UILabel alloc]initWithFrame:CGRectMake(40*PERCEN, 0, scrollView.width-80*PERCEN, scrollView.height)];
        contentLb.backgroundColor = [UIColor clearColor];
        contentLb.textAlignment = NSTextAlignmentCenter;
        contentLb.textColor = [UIColor whiteColor];
        contentLb.font = [UIFont systemFontOfSize:12.f];
        contentLb.attributedText = mutStr;
        contentLb.numberOfLines = 0;
        [scrollView addSubview:contentLb];
        float height =[mutStr boundingRectWithSize:CGSizeMake(contentLb.width, 20000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:NULL].size.height;
        
        contentLb.height = height;
        scrollView.contentSize = CGSizeMake(scrollView.width, height);
    } else {
        scrollView.contentSize = CGSizeMake(scrollView.width, scrollView.height);
    }
    
    if (_dataDic) {
        NSString *imgUrl = [_dataDic objectForKey:@"PicPath"];
        UIImage *imgs = [UIImage imageNamed:@"qzx_player_bg"];
        if (![imgUrl isKindOfClass:[NSNull class]]) {
            [_bgImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,imgUrl]] placeholderImage:imgs options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                _bgImgView.image = [self getCenterImg:image withImgView:_bgImgView];
            }];
        } else {
            _bgImgView.image = imgs;
        }
    }
//    _bgImgView.contentMode = UIViewContentModeScaleAspectFit;
    
    UIImage *img = [UIImage imageNamed:@"bofang"];
    _contentBt = [UIButton buttonWithType:UIButtonTypeCustom];
    _contentBt.backgroundColor = [UIColor clearColor];

    _contentBt.frame = CGRectMake(0, 0, scrollView.width, 806*PERCEN_HEIGHT);
    [_contentBt setImage:img forState:UIControlStateNormal];
    [_contentBt setImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateSelected];

    [_contentBt addTarget:self action:@selector(onSelectForPlayerAction:) forControlEvents:UIControlEventTouchUpInside];
    _contentBt.hidden = YES;
    [_showContentLb addSubview:_contentBt];
    
    
}

#pragma mark - Actions
#pragma mark - 点击录音
- (IBAction)record:(UIButton *)sender {
    _identityType++;
    if (self.reRecord == sender) {
        //是重按按钮
        _identityType = 0;
    }
    
    self.reRecord.hidden = YES;
    self.promulgate.hidden = YES;
    if (_identityType == 3) {
        _identityType = 1;
    }
    
    if (_identityType == IdentityType_record) {
        //起始
        [sender setTitle:@"录音" forState:UIControlStateNormal];
        [sender setTitleColor:TINK_BG_COLOR forState:UIControlStateNormal];
        [sender setBackgroundImage:[UIImage imageNamed:@"jixuluyin"] forState:UIControlStateNormal];
        
        //重录 数据清空
        _recordShowTitleLb.text = @"准备录制00:00/15:00";
        secondIndex = 0;
        [_sliderView setValue:(1. * secondIndex / 900) animated:YES];
        
        [_audioRecorder stop];
        NSFileManager *fileManager = [[NSFileManager alloc]init];
        if ([fileManager fileExistsAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)]) {
            [fileManager removeItemAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME) error:nil];
        }
        [self setRecorderURL:[NSURL fileURLWithPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)] withSettings:nil];
        
        if (_recordTimer) {
            [_recordTimer invalidate];
            _recordTimer = nil;
        }
        _recordTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onRecordMusic) userInfo:nil repeats:YES];
        
        _contentBt.hidden = YES;
    }
    else if (_identityType == IdentityType_pauseRecord) {
        //开始录音
        [sender setTitle:@"暂停录音" forState:UIControlStateNormal];
        [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sender setBackgroundImage:[UIImage imageNamed:@"zantingluyin"] forState:UIControlStateNormal];
//        _recordShowTitleLb.text = @"正在录制00:00/15:00";
        if (_audioPlayer) {
            [_audioSession setActive:NO error:nil];
            [_audioPlayer stop];
            [_audioPlayer prepareToPlay];
            _audioPlayer = nil;
        }
        if (_audioSession) {
            [_audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
            [_audioSession setActive:YES error:nil];
        }
        [_audioRecorder record];
        [_sliderView setValue:(1. * secondIndex / 900) animated:YES];
        if (!_recordTimer) {
            _recordTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onRecordMusic) userInfo:nil repeats:YES];
        }
        _contentBt.hidden = YES;
        _contentBt.selected = NO;
    }
    else if (_identityType ==IdentityType_continueRecord) {
        //暂停了
        [sender setTitle:@"继续录音" forState:UIControlStateNormal];
        [sender setTitleColor:TINK_BG_COLOR forState:UIControlStateNormal];
        [sender setBackgroundImage:[UIImage imageNamed:@"jixuluyin"] forState:UIControlStateNormal];
        
        int second = (int)secondIndex / 60;
        int minter = (int)secondIndex % 60;
        _recordShowTitleLb.text = [NSString stringWithFormat:@"准备录制%02d:%02d/15:00",second,minter];
        if (_recordTimer) {
            [_recordTimer invalidate];
            _recordTimer = nil;
        }
        
        [_audioRecorder pause];
        
        self.reRecord.hidden = NO;
        self.promulgate.hidden = NO;
        _contentBt.hidden = NO;
    }
}

- (void)onRecordMusic
{
    if (_identityType == IdentityType_pauseRecord) {
        if (secondIndex >= 15*60) {
            //到了15分钟结束
            if (_recordTimer) {
                [_recordTimer invalidate];
                _recordTimer = nil;
            }
            [ErrorMessage showErrorMessage:@"最多录制15分钟" inView:self.view];
            [self record:_recordButton];
            return;
        }
        ++secondIndex;
        int second = (int)secondIndex / 60;
        int minter = (int)secondIndex % 60;
        _recordShowTitleLb.text = [NSString stringWithFormat:@"正在录制%02d:%02d/15:00",second,minter];
        
        [_sliderView setValue:(1. * secondIndex / 900) animated:YES];
    }
    else if (_identityType == IdentityType_continueRecord) {
       float value =  _audioPlayer.currentTime/900.0;
       [_sliderView setValue:value animated:YES];
        
        int second = (int)_audioPlayer.currentTime / 60;
        int minter = (int)_audioPlayer.currentTime % 60;
        _recordShowTitleLb.text = [NSString stringWithFormat:@"正在播放%02d:%02d/15:00",second,minter];
        
        if (second * 60 + minter >= secondIndex) {
            //播放超过录制时间十，暂停
            if (_recordTimer) {
                [_recordTimer invalidate];
                _recordTimer = nil;
            }
            [self onSelectForPlayerAction:_contentBt];
            return;
        }
    }
    
}

- (void)setRecorderURL:(NSURL *)urlPath withSettings:(NSDictionary *)settings
{
    
    if (!_audioSession) {
        _audioSession = [AVAudioSession sharedInstance];
    }
    [_audioSession setActive:YES error:nil];
    /*
     当你在只录音的时候可以讲category设置为AVAudioSessionCategoryRecord
     需要录音并播放的时候设置AVAudioSessionCategoryPlayAndRecord；
     需要播放的时候设置AVAudioSessionCategoryPlayback。
     */
    [_audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
    //设置播放器为扬声器模式
    [_audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
    
    
    if (!settings) {
        NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc]initWithCapacity:10];
        [recordSettings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
        [recordSettings setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];//采样率
        [recordSettings setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];//通道的数目,1单声道,2立体声
//        [recordSettings setValue:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];//解码率
//        [recordSettings setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];//采样位 8/16/24/32
        [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
//        [recordSettings setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
//        [recordSettings setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
        
        settings = recordSettings;
    }
    
    NSError *error = nil;
    if (!_audioRecorder) {
        _audioRecorder = [[AVAudioRecorder alloc]initWithURL:urlPath settings:settings error:&error];
        _audioRecorder.delegate = self;
    }
    if ([_audioRecorder prepareToRecord] == YES){
      
    }else {
        int errorCode = CFSwapInt32HostToBig ((int)[error code]);
        NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode);
    }

}

#pragma mark - 播放
- (void)onSelectForPlayerAction:(UIButton *)bt
{
    NSLog(@"播放");
    bt.selected = !bt.selected;
    
    if (_audioSession) {
        [_audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        [_audioSession setActive:NO error:nil];
    }
    NSString *filePath = RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME);
    
    if (!_audioPlayer) {
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:nil];
        _audioPlayer.delegate = self;
    }

    if (bt.selected) {
        [_audioPlayer prepareToPlay];
        [_audioPlayer play];
        [_sliderView setValue:0 animated:YES];
        
        int second = (int)_audioPlayer.currentTime / 60;
        int minter = (int)_audioPlayer.currentTime % 60;
        _recordShowTitleLb.text = [NSString stringWithFormat:@"正在播放%02d:%02d/15:00",second,minter];
        if (!_recordTimer) {
            _recordTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onRecordMusic) userInfo:nil repeats:YES];
        }
    } else {
        [_audioPlayer pause];
        if (_recordTimer) {
            [_recordTimer invalidate];
            _recordTimer = nil;
        }
    }

}

#pragma mark - AVAudioRecorderDelegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    if (flag) {
        [_audioSession setActive:NO error:nil];
    }
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error
{
    if (error) {
        [_audioSession setActive:NO error:nil];
    }
}


#pragma mark - 发布亲子秀
- (IBAction)sendShow:(id)sender {
    
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    if ([fileManager fileExistsAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)]) {
//        dispatch_async(dispatch_get_main_queue(), ^{
        
            [[UserManager standerDefult]transformCAFToMP3WithPath:MusicCachesDirectory withNormalName:MUSIC_PRIVATE_NAME withFileName:self.titleString WithComplate:^{
                
                if ([UserManager standerDefult].mainPlayer && [UserManager standerDefult].isBackPlay) {
                    [_audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
                    [[UserManager standerDefult].mainPlayer play];
                }
                
                 NSString *mp3FilePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",MUSIC_PRIVATE_NAME]];
                MBSendShowController *sendShowVC = [[MBSendShowController alloc] init];
                sendShowVC.dataDic = _dataDic;
                sendShowVC.recordPath = mp3FilePath;
                sendShowVC.isFormFreedom = NO;
                sendShowVC.activityId = @"0";
                [self.navigationController pushViewController:sendShowVC animated:YES];
                
            } withFaild:^{
               
            }];
//        });
    }
    
    
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{

    _audioPlayer = nil;
    _contentBt.selected = NO;
}

- (void)onBack
{
    //对录制文件删除
    if (_audioRecorder) {
        [_audioRecorder stop];
        _audioRecorder = nil;
    }
    if (_audioSession) {
        [_audioSession setActive:NO error:nil];
        if ([UserManager standerDefult].mainPlayer && [UserManager standerDefult].isBackPlay) {
            [_audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
            [[UserManager standerDefult].mainPlayer play];
        }
        _audioSession = nil;
    }
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    if ([fileManager fileExistsAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME)]) {
        [fileManager removeItemAtPath:RECORD_MUSIC_PATH(MUSIC_PRIVATE_NAME) error:nil];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onGoToBack
{
    if (isBack == NO) {
        isBack = YES;
        [self onBack];
    }
}

- (void)onSendQZShowAction
{
    MBPlayShowController *playShowVC = [[MBPlayShowController alloc] init];
    [self.navigationController pushViewController:playShowVC animated:YES];
}
@end
